
import deepClone from './deepClone'
/**
 * 将树形结构转成数组结构
 * @param {Array} treeData  数据源
 * @param {Object} treeProps 树结构配置 { id : "menu_id", children : "children" }
 * lz.treeToArray(treeData);
 */
interface treeData {
	id ?: number | string,
	children ?: Array<treeData>
}
interface treeProps {
	id ?: number | string,
	parent_id ?: number | string,
	children ?: Array<treeProps>
	deleteChildren?:boolean
}
export const treeToArray = (treeData : Array<treeData>, treeProps : IObject<treeProps>) => {
    // const newTreeData = deepClone(treeData)
    const newTreeData = JSON.parse(JSON.stringify(treeData))
    return treeToArrayFn(newTreeData, treeProps, [], '')
}
const treeToArrayFn = (treeData : Array<treeData>, treeProps : IObject<treeProps>, arr = [], current_parent_id:string) => {
    const { id = '_id', parent_id = 'parent_id', children = 'children', deleteChildren = true } = treeProps
    for (const i in treeData) {
        const item = treeData[i]
        if (current_parent_id) item[parent_id] = current_parent_id
        arr.push(item)
        if (item[children] && item[children].length > 0) {
            arr = treeToArrayFn(item[children], treeProps, arr, item[id])
        }
        if (deleteChildren) {
            delete item[children]
        }
    }
    return arr
}
/**
 * 数组结构转树形结构
let tree = lz.arrayToTree(arrayData,{
	id:"code", 
	parent_id:"parent_code",
});
 */
interface OriginalArrayData {
  id ?: number | string;
  parent_id ?: number | string;
  // 可以添加其他可能需要排序的字段
}

interface TreeProps {
  id ?: number | string;
  parent_id ?: number | string;
  children ?: string;
  sortField ?: string; // 排序字段
  sortOrder ?: 'asc' | 'desc'; // 排序方向
}

export const arrayToTree = (originalArrayData:Array<OriginalArrayData>, treeProps:TreeProps) => {
  const arrayData = JSON.parse(JSON.stringify(originalArrayData));
  let { 
    id = '_id', 
    parent_id = 'parent_id',
    children = 'children',
    deleteParentId = false,
    sortField,
    sortOrder = 'asc',
    need_field
  } = treeProps;

  // 如果提供了排序字段，则对数组进行排序
  if (sortField) {
    arrayData.sort((a, b) => {
      if (a[sortField] === b[sortField]) return 0;
      return (a[sortField] > b[sortField] ? 1 : -1) * (sortOrder === 'asc' ? 1 : -1);
    });
  }

  const result = [];
  const temp = {};
  for (let i = 0; i < arrayData.length; i++) {
    temp[arrayData[i][id]] = arrayData[i];
  }

  for (let j = 0; j < arrayData.length; j++) {
    const currentElement = arrayData[j];
    
    if (need_field) {
      need_field = uniqueArr(need_field.concat([id, parent_id, children]));
      for (const keyName in currentElement) {
        if (need_field.indexOf(keyName) === -1) {
          delete currentElement[keyName];
        }
      }
    }

    const tempCurrentElementParent = temp[currentElement[parent_id]];
    if (tempCurrentElementParent) {
      if (!tempCurrentElementParent[children]) {
        tempCurrentElementParent[children] = [];
      }
      if (deleteParentId) {
        delete currentElement[parent_id];
      }
      tempCurrentElementParent[children].push(currentElement);
    } else {
      result.push(currentElement);
    }
  }

  return result;
};

// 最简单数组去重法
function uniqueArr(array:Array<any>) {
    const n = [] // 一个新的临时数组
    // 遍历当前数组
    for (let i = 0; i < array.length; i++) {
        // 如果当前数组的第i已经保存进了临时数组，那么跳过，
        // 否则把当前项push到临时数组里面
        if (n.indexOf(array[i]) == -1) n.push(array[i])
    }
    return n
}